package com.wframe.project.former.web.products;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.metadata.wordbook.WordbookService;
import com.frame.pageform.DataPageForm;
import com.frame.pageform.ResponseUtils;
import com.frame.pageform.annotation.Login;
import com.wframe.project.former.dataservices.products.ProductClassService;
import com.wframe.project.former.dataservices.products.ProductService;
import com.wframe.project.former.dataservices.sysman.SysmanService;
import com.wframe.project.former.dataservices.upload.UploadService;
import com.wframe.project.former.entity.ProductPriceAttrVo;
import com.wframe.project.former.entity.ProductsAttrvalBean;
import com.wframe.project.former.entity.ProductsPricesBean;
import com.wframe.project.former.enums.ProductAttrTagEnum;
import com.wframe.project.jnd.util.WebUtils;

/**
 * 功能:商品管理<br>
 * 参数:<br>
 * 作者:王海锋<br>
 * 时间:2017-1-13上午10:58:55<br>
 */
@Login
public class ProductPage extends DataPageForm {

    private JdataBean bean;
    private String edit;
    private ProductService service = ProductService.getIntance();
    private final String baseClasCode = "1";

    /**
     * 商品管理列表页
     */
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        return "/webadmin/product/productMan.jsp";
    }

    /**
     * 商品列表
     *
     * @return
     * @throws Exception
     */
    public String productList() throws Exception {
        PageResult pr = service.queryProducts(bean, getPageSize_(), getPageNum());
        ProductClassService pcservice = ProductClassService.getIntance();

        List<JdataBean> list = pr.getList();
        for (JdataBean product : list) {
            List<JdataBean> jdataBeans = service.queryAllModelAttrAndVal("1", String.valueOf(product.get("id")), 1);
            for (JdataBean attr : jdataBeans) {
                product.put(attr.getString("code"), attr.get("val"));
            }

            product.put("classname", pcservice.getProductClassName(product.getString("id")));
        }

        setPagination(pr);
        return "/webadmin/product/productList.jsp";
    }

    /**
     * 功能:加载商品列表数据<br>
     * 参数:<br>
     * 作者:王海锋<br>
     * 时间:2017-1-9下午11:16:14<br>
     */
    public String loadProducts() throws Exception {
        int pageno = 1;
        int size = 20;
        if (StringUtils.isNotBlank(getRequest().getParameter("page")))
            pageno = new Integer(getRequest().getParameter("page"));
        if (StringUtils.isNotBlank(getRequest().getParameter("rows")))
            size = new Integer(getRequest().getParameter("rows"));
        PageResult pr = service.queryProducts(bean, size, pageno);
        getJsonObject().put("total", pr.getResultCount());
        getJsonObject().put("rows", pr.getList());
        return getJsonObject().toString();
    }

    /**
     * 功能:加载商品及价格属性列表数据<br>
     * 参数:<br>
     * 作者:王海锋<br>
     * 时间:2017-1-9下午11:16:14<br>
     */
    public String loadProductPrices() throws Exception {
        int pageno = 1;
        int size = 20;
        if (StringUtils.isNotBlank(getRequest().getParameter("page")))
            pageno = new Integer(getRequest().getParameter("page"));
        if (StringUtils.isNotBlank(getRequest().getParameter("rows")))
            size = new Integer(getRequest().getParameter("rows"));
        if (bean != null && StringUtils.isNotBlank(bean.getString("rows"))) size = bean.getInt("rows");
        PageResult pr = service.queryProductPrices(bean, size, pageno);
        getJsonObject().put("total", pr.getResultCount());
        getJsonObject().put("rows", pr.getList());
        return getJsonObject().toString();
    }

    @Override
    /**
     * 商品详情编辑页
     */
    public String show() throws Exception {
        // TODO Auto-generated method stub
        String edit = bean.getString("edit");
        if (StringUtils.isNotBlank(bean.getString("id"))) {
            String classid = bean.getString("classid");
            bean = service.getBean(bean.getString("id"));
            if (StringUtils.isBlank(classid))
                bean.put("classid", service.getProductClass(bean.getString("id")).getString("classid"));
            else bean.put("classid", classid);
        } else {
            bean.put("code", service.createProductCode(bean.getString("classid")));
        }
        bean.put("edit", edit);
        JdataBean classbean = ProductClassService.getIntance().getBean(bean.getString("classid"));
        if (classbean != null && !baseClasCode.equals(bean.getString("classid"))) {
            getRequest().setAttribute("base_attrs", service.queryAllModelAttrAndVal(classbean.getString("code"), bean.getString("id"), ProductAttrTagEnum.Base.getTag()));
            getRequest().setAttribute("comm_attrs", service.queryAllModelAttrAndVal(classbean.getString("code"), bean.getString("id"), ProductAttrTagEnum.Comm.getTag()));
            getRequest().setAttribute("sale_attrs", service.queryAllModelAttrAndVal(classbean.getString("code"), bean.getString("id"), ProductAttrTagEnum.Sale.getTag()));
            bean.put("classnavs", ProductClassService.getIntance().getProductClassNav(classbean.getString("code")));
        }
        if (StringUtils.isBlank(bean.getString("classid")))
            getRequest().setAttribute("base_attrs", service.queryAllModelAttrAndVal(baseClasCode, bean.getString("id"), ProductAttrTagEnum.Base.getTag()));

        getRequest().setAttribute("controlsales", service.queryControlsales(bean.getString("id")));
        getRequest().setAttribute("controlUsers", service.queryControlUsers(bean.getString("id")));
        getRequest().setAttribute("priceGrades", service.queryPricegrade(bean.getString("id")));
        return "/webadmin/product/productEdit.jsp";
    }


    @Override
    public String toDel() throws Exception {
        // TODO Auto-generated method stub
        service.delProduct(bean.getString("id"));
        return getJsonObject().toString();
    }

    /**
     * 保存商品信息
     */
    @Override
    public boolean toUpdate() throws Exception {
        try {
            JdataBean basedata = new JdataBean();
            basedata.put("id", bean.getString("id"));
            basedata.put("name", bean.getString("name"));
            basedata.put("classid", bean.getString("classid"));
            basedata.put("code", bean.getString("code"));
            basedata.put("details", bean.getString("details"));
            basedata.put("shuombook", bean.getString("shuombook"));
            basedata.put("aboutus", bean.getString("aboutus"));
            basedata.put("orderno", bean.getString("orderno"));
            basedata.put("unit", bean.getString("unit"));
            basedata.put("unitname", bean.getByDict("unit", "ProductUnit"));

            List<ProductsAttrvalBean> attrList = new ArrayList<ProductsAttrvalBean>();
            Object[] keys = bean.getDataMap().keySet().toArray();
            for (Object key : keys) {
                if (key.toString().startsWith("attrs_")) {
                    //动态属性值
                    String attid = key.toString().replace("attrs_", "");
                    String attrval = bean.getString(key.toString());
                    if (StringUtils.isNotBlank(attrval))
                        attrList.add(new ProductsAttrvalBean(new Integer(attid), ResponseUtils.filter(attrval.replaceAll(",", ""))));
                }
            }
            String saleattrs = bean.getString("saleattrs");//销售属性信息
            String[] mainphotos = null;//主商品图片信息
            List<ProductsPricesBean> priceList = new ArrayList<ProductsPricesBean>();
            if (StringUtils.isNotBlank(saleattrs)) {
                JSONArray arr = new JSONArray(saleattrs);
                for (int i = 0; i < arr.length(); i++) {
                    JSONObject obj = arr.getJSONObject(i);
                    ProductsPricesBean pricebean = new ProductsPricesBean();
                    String attrcodestr = obj.getString("attrcodes");
                    if (StringUtils.isNotBlank(obj.getString("id")))
                        pricebean.setId(new Integer(obj.getString("id")));
                    pricebean.setName(getModelAttrName(attrcodestr));
                    pricebean.setAttrcodes(attrcodestr);
                    if (StringUtils.isNotBlank(obj.getString("price")))
                        pricebean.setPrice(obj.getDouble("price"));
                    if (StringUtils.isNotBlank(obj.getString("price_s"))) {
                        pricebean.setPrice_s(obj.getDouble("price_s"));
                        if (pricebean.getPrice() == null)
                            pricebean.setPrice(obj.getDouble("price_s"));
                    }
                    if (StringUtils.isNotBlank(obj.getString("amount")))
                        pricebean.setAmount(obj.getInt("amount"));

                    if (StringUtils.isNotBlank(obj.getString("djamount"))) {
                        pricebean.setDjamount(obj.getInt("djamount"));
                    } else {
                        pricebean.setDjamount(0);
                    }

                    String photo = obj.getString("photos");
                    if (StringUtils.isNotBlank(photo)) {
                        String[] photos = photo.split(",");
                        pricebean.setPhoto(photos[0]);//第一张设置为主图片
                        pricebean.setPhotodataids(photos);
                        if ("0".equals(obj.getString("attrcodes"))) mainphotos = photos;
                    }
                    priceList.add(pricebean);
                }
            }
            if (mainphotos != null && mainphotos.length > 0) {
                basedata.put("photo", mainphotos[0]);//第一张设置为主图片
                basedata.put("photos", mainphotos);
            }
            JdataBean attrdata = new JdataBean();
            attrdata.put("attrList", attrList);
            attrdata.put("priceList", priceList);

            String productid = service.saveProduct(basedata, attrdata);

            JSONArray controlsales = null;
            if (StringUtils.isNotBlank(bean.getString("controlsales")))//保存控销数据
                controlsales = new JSONArray(bean.getString("controlsales"));
            service.addControlsales(productid, controlsales, bean.getString("controlusers"));
            if (StringUtils.isNotBlank(bean.getString("gradeprices"))) {//保存价格等级
                JSONArray gradeprices = new JSONArray(bean.getString("gradeprices"));
                service.savePricegrade(productid, gradeprices);
            }

            getJsonObject().put("state", "ok");
        } catch (Exception e) {
            Logger.getLogger(this.getClass()).error("保存商品信息错误：", e);
            getJsonObject().put("state", e.getMessage());
        }
        return false;
    }

    /**
     * 功能:加载商品已保存销售属性信息<br>
     * 参数:<br>
     * 作者:王海锋<br>
     * 时间:2017-1-17下午02:57:55<br>
     *
     * @throws Exception
     */
    public String loadSaleattrs() throws Exception {
        getJsonObject().put("attrs", service.queryProductsPrices(bean.getString("productid")));
        getJsonObject().put("prophotos", UploadService.getIntance().queryPhotos(bean.getString("dataid")));//商品图片
        return getJsonObject().toString();
    }

    /**
     * 商品上架
     *
     * @return
     * @throws Exception
     */
    public String shelves() throws Exception {
        service.shelves(getPrimaryKey_());
        return getJsonObject().toString();
    }

    /**
     * 商品下架
     *
     * @return
     * @throws Exception
     */
    public String offshelf() throws Exception {
        service.offshelf(getPrimaryKey_());
        return getJsonObject().toString();
    }

    /**
     * 库存管理
     *
     * @return
     * @throws Exception
     */
    public String inStockList() throws Exception {
        setPagination(service.queryStockList(bean, getPageSize_(), getPageNum()));
        return "/webadmin/product/stockList.jsp";
    }

    public String inStock_Show() throws Exception {
        bean = service.getProductsPrices(bean.getString("id"));
        return "/webadmin/product/stockEdit.jsp";
    }

    public String inStock_update() throws Exception {
        String id = bean.getString("attrid");
        bean.remove("attrid");
        bean.put("amount", bean.get("totalamount"));
        bean.remove("totalamount");
        service.updateProductsPrices(id, bean);
        getJsonObject().getJsonPage().showOkMsg("修改成功");
        getJsonObject().getJsonPage().closeWin("ok");
        return getJsonObject().toString();
    }

    /**
     * 功能:将销售属性拼接描述字符串<br>
     * 参数:attrcodestr格式（多销售属性用|隔开）：属性id:属性值code,属性值code,属性值code<br>
     * 作者:王海锋<br>
     * 时间:2017-1-17上午10:11:27<br>
     *
     * @throws Exception
     */
    public String getModelAttrName(String attrcodestr) throws Exception {
        List<String> attrcodes = new ArrayList<String>();
        if ("0".equals(attrcodestr)) return "";
        List<ProductPriceAttrVo> volist = new WebUtils().strToPriceAttrVo(attrcodestr);
        for (ProductPriceAttrVo vo : volist) {
            for (String code : vo.getItemcodes()) attrcodes.add(code);
        }
        String name = "";
        List<JdataBean> items = ProductClassService.getIntance().queryModelAttrItemByCodes(attrcodes);
        for (JdataBean item : items) {
            if (!"".equals(name)) name += " ";
            name += item.getString("text");
        }
        return name;
    }

    /**
     * 进入添加控销页面
     *
     * @return
     * @throws Exception
     */
    public String addControlsalesShow() throws Exception {
        if (bean == null) {
            bean = new JdataBean();
            bean.put("type", 1);
        }
        if (bean.getInt("type") == 1)
            setResultList_(WordbookService.getIntance().queryItem("UserGroup"));
        else if (bean.getInt("type") == 2)
            setResultList_(WordbookService.getIntance().queryItem("PriceGrade"));
        else if (bean.getInt("type") == 3)
            setResultList_(SysmanService.getIntance().queryAreatrad());
        return "/webadmin/product/controlsalesEdit.jsp";
    }

    public String hotlist() throws Exception {
        setPagination(service.queryHotProducts(bean, getPageSize_(), getPageNum()));
        return "/webadmin/product/hotlist.jsp";
    }

    public String hotShow() throws Exception {

        return "/webadmin/product/hotshow.jsp";
    }

    public String loadHotProducts() throws Exception {
        int pageno = 1;
        int size = 20;
        if (StringUtils.isNotBlank(getRequest().getParameter("page")))
            pageno = new Integer(getRequest().getParameter("page"));
        if (StringUtils.isNotBlank(getRequest().getParameter("rows")))
            size = new Integer(getRequest().getParameter("rows"));
        PageResult pr = service.queryHotProducts(bean, size, pageno);
        getJsonObject().put("total", pr.getResultCount());
        getJsonObject().put("rows", pr.getList());
        return getJsonObject().toString();
    }

    public String hotSave() throws Exception {
        String[] proids = null;
        if (StringUtils.isNotBlank(bean.getString("proids"))) proids = bean.getString("proids").split(",");
        bean.remove("proids");
        service.addHotProducts(proids);
        getJsonObject().getJsonPage().closeWin("ok");
        return getJsonObject().toString();
    }

    public String hotDel() throws Exception {
        service.delHotProduct(getPrimaryKey_());
        return getJsonObject().toString();
    }

    public String hotStatus() throws Exception {
        service.hotProductStatus(getPrimaryKey_(), bean.getInt("setstatus"));

        return getJsonObject().toString();
    }

    public JdataBean getBean() {
        return bean;
    }

    public void setBean(JdataBean bean) {
        this.bean = bean;
    }


    public String getEdit() {
        return edit;
    }

    public void setEdit(String edit) {
        this.edit = edit;
    }

}
